package com.springboot.exception.handler;

import com.springboot.exception.dto.ErrorInfo;
import com.springboot.exception.exception.MyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liuwei
 * @version 2017/7/15 下午11:05
 * @modified TODO
 * @description 统一的异常处理类
 * @see
 * @since 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultExceptionHandler(HttpServletRequest request , Exception e){
        ModelAndView model = new ModelAndView();
        model.addObject("exception",e);
        model.addObject("url" , request.getRequestURL());
        model.setViewName("error");
        return model;
    }

    @ExceptionHandler(value = MyException.class)
    public @ResponseBody ErrorInfo jsonExceptionHandler(HttpServletRequest request , MyException e){
        ErrorInfo error = new ErrorInfo();
        error.setCode("9999");
        error.setMessage("系统异常");
        error.setUrl(request.getRequestURL().toString());
        return error;
    }
}
